package cn.xiuxius.embedded.command.flash;

import lombok.extern.slf4j.Slf4j;
import picocli.CommandLine;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

@CommandLine.Command(name = "base",
        description = "Base flush command",
        mixinStandardHelpOptions = true
)
@Slf4j
public class BaseFlashCommand implements Callable<Integer> {

    @CommandLine.ParentCommand
    private FlashCommand flashCommand;

    @CommandLine.Mixin
    private FlashCommandOptions options;

    public FlashCommandOptions getOptions() {
        return flashCommand.getOptions();
    }

    @Override
    public Integer call() {
        if (flashCommand == null) {
            CommandLine.usage(this, System.out);
            return 1;
        }
        if (flashCommand.prepare() != 0) {
            return 1;
        }
        log.info("------------------ Download & Flash Target Start ------------------");
        List<String> command = new ArrayList<>();
        command.add(flashCommand.getStcgal().getAbsolutePath());
        command.add("-P");
        command.add(getOptions().getChipProtocol());
        command.add("-p");
        command.add(getOptions().getPortName());
        command.add(flashCommand.getHexFile().getAbsolutePath());
        log.info("Executing command: {}", String.join(" ", command));
        //构建任务
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        Process process = null;
        pb.redirectErrorStream(true); // 合并 stdout 和 stderr
        try {
            process = pb.start();
            log.info("⏳♻️ Waiting for device reset...");
            // 实时打印 stcgal 输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info("[stcgal] {}", line);
                }
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                log.error("Flush failed: {}", exitCode);
                return 1;
            } else {
                log.info("✅ Flush completed!");
                log.info("----------------------- Download & Flash Target End -------------------------------");
                return 0;
            }

        } catch (Exception e) {
            return 1;
        }finally {
            if (process != null) {
                process.destroyForcibly();
            }
        }
    }



}
